<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .editor-box {
      width: 500px;
      height: 500px;
      background-color: red;
    }
  </style>
</head>

<body>
  <div class="editor-box" id="editor-box" contenteditable="true" >
    可以直接粘贴图片到这里直接上传
</div>
  <button type="button" id="btn-submit">上 传</button>
<script>
    //光标处插入 dom 节点
    function  insertNodeToEditor(editor,ele) {
      //插入dom 节点
      var range;//记录光标位置对象
      var node = window.getSelection().anchorNode;
      // 这里判断是做是否有光标判断，因为弹出框默认是没有的
      if (node != null) {
          range = window.getSelection().getRangeAt(0);// 获取光标起始位置
          range.insertNode(ele);// 在光标位置插入该对象
      } else {
          editor.append(ele);
      }
  }
  
  var box = document.getElementById('editor-box');
  //绑定paste事件
  box.addEventListener('paste',function (event) {
      var data = (event.clipboardData || window.clipboardData);

      var items = data.items;
      var fileList = [];//存储文件数据
      if (items && items.length) {
          // 检索剪切板items
          for (var i = 0; i < items.length; i++) {
              console.log(items[i].getAsFile());
              fileList.push(items[i].getAsFile());
          }   
      }

      window.willUploadFileList = fileList;
      event.preventDefault();//阻止默认行为

      submitUpload();
  }); 

  function submitUpload() {

      var fileList = window.willUploadFileList||[];
      var fd = new FormData();   //构造FormData对象
      for(var i =0;i<fileList.length;i++){
          fd.append('f1', fileList[i]);//支持多文件上传
      }
      var xhr = new XMLHttpRequest();   //创建对象
      xhr.open('POST', 'http://localhost:8100/', true);
      xhr.onreadystatechange = function () {
          if (xhr.readyState === 4) {
              var obj = JSON.parse(xhr.responseText);   //返回值
              console.log(obj);
              if(obj.fileUrl.length){
                  var img = document.createElement('img');
                  img.src= obj.fileUrl[0];
                  img.style.width='100px';
                  insertNodeToEditor(box,img);
                 // alert('上传成功');
              }
          }
      }

      xhr.send(fd);//发送
  }

</script>
</body>

</html>